//
//  SkQueue.swift
//  RHello
//
//  Created by 吴非 on 2022/3/16.
//  Copyright © 2022 Lanchc. All rights reserved.
//

import UIKit
import CocoaAsyncSocket

class SkQueue: NSObject {
    
    static let `default` = SkQueue()
    
    weak var tx: UITextView?

    // 扫描设备
    func scanningDevice(bIndex:Int, eIndex: Int,  callbackHandle: @escaping () -> Void) {
        print("任务--> 1")
        // 依次是：主队列，并行队列，串行队列
        // 主队列
        //            let queue = DispatchQueue.main
        // 并行队列
        let queue = DispatchQueue(label: "label", attributes: .concurrent)
        // 串行队列
        //            let queue = DispatchQueue(label: "label")
        
        let group = DispatchGroup()
        
        for index in bIndex ..< eIndex {
            // 同步异步的切换
            //                queue.sync {
            queue.async {
                
                group.enter()//加入组
                
                                  
                //                if Thread.current == Thread.main {
                //                    print("是主线程")
                //                }else {
                let temp_c = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.global())
                let temp_ip: String = "192.168.1.\(index)"
                try? temp_c.connect(toHost: temp_ip, onPort: UInt16(2001), withTimeout: 10)
                
                print("不是主线程#\(temp_ip)# 任务开始")
                sleep(4)
//                print("不是主线程#\(temp_ip)# 任务结束")
                temp_c.disconnect()
//                print("不是主线程#\(temp_ip)# 断开链接")
                //                }
                print("队列中的任务---> \(index)")
                
                group.leave()//离开
            }
        }
        print("#### ===> 任务---> 2")
        
        // 调度组里的任务都执行完毕执行
        group.notify(queue: queue) {
            
            let tempVip = SkManager.default.askCurrentLinkIp()
            if tempVip.isEmpty {
                print("没有解析到，接续")
                sleep(3)
                callbackHandle()
            } else {
                print("解析到设备，停止")
                callbackHandle()
            }
        }
        
        
        
    }
    
    func askDemo() -> Void {
        let temp_c = GCDAsyncSocket(delegate: self, delegateQueue: DispatchQueue.global())
        let temp_ip: String = "www.baidu.com"
        try? temp_c.connect(toHost: temp_ip, onPort: UInt16(2001), withTimeout: 10)
        sleep(2)
        temp_c.disconnect()
    }
    
}

extension SkQueue: GCDAsyncSocketDelegate {
    
    
    /// 链接成功
    func socket(_ sock: GCDAsyncSocket, didConnectToHost host: String, port: UInt16) {
        
        
        print("链接成功！")
        SkManager.default.writeInLinkIp(hostURL: host)
        DispatchQueue.main.async { [weak self] in
            guard let wkThis = self else { return }
             /// 保存ip
            wkThis.showMessage("链接成功 => \(host)")
            print("链接成功 => \(host)")
        }
        
        
       
    }
    
    /// 接受消息
    func socket(_ sock: GCDAsyncSocket, didRead data: Data, withTag tag: Int) {
        
        //        let text = String(data: data, encoding: .utf8)
        //
        //        showMessage(text!)
        //
        //        clientSocket.readData(withTimeout: -1, tag: 0)
    }
    /// 断开链接
    func socketDidDisconnect(_ sock: GCDAsyncSocket, withError err: Error?) {
        
        print("断开链接=> \(String(describing: sock.localHost))")
    }
    
    func sendMessage(bc: String) {
        // tag: message tag
        //        clientSocket.write( bc.data(using: .utf8), withTimeout: -1, tag: 0)
    }
    
    // 现实消息
    func showMessage(_ str: String) {
        guard let txt = tx else { return  }
        txt.text = txt.text.appendingFormat("%@\n", str)
    }
}
